/*
 * Ext JS Library 2.2
 * Copyright(c) 2006-2008, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */
 
 cp = new Ext.state.CookieProvider({
       path: "/",
       expires: new Date(new Date().getTime()+(1000*60*60*24*360)) //360 days
   })
   Ext.state.Manager.setProvider(cp);
   
   
var dfeeds = new Array();
FeedPanel = function() {
    FeedPanel.superclass.constructor.call(this, {
        id:'feed-tree',
        region:'west',
        title:'Иточники',
        split:true,
        width: 250,
        minSize: 175,
        maxSize: 400,
        collapsible: true,
        margins:'0 0 5 5',
        cmargins:'0 5 5 5',
        rootVisible:false,
        lines:false,
        autoScroll:true,
        root: new Ext.tree.TreeNode('Feed Viewer'),
        collapseFirst:false,
		useArrows: true,
        tbar: [{
            iconCls:'add-feed',
            text:'Добавить',
            handler: this.showWindow,
            scope: this
        },{
            id:'delete',
            iconCls:'delete-icon',
            text:'Удалить',
            handler: function(){
                var s = this.getSelectionModel().getSelectedNode();
                if(s){
                    this.removeFeed(s.attributes.url);
                }
            },
            scope: this
        }]
    });

    this.feeds = this.root.appendChild(
        new Ext.tree.TreeNode({
            text:'Мои источники',
            cls:'feeds-node',
			id: 'myfeedstree',
            expanded:true
        })
    );
	
	 var container = this;
	
    this.getSelectionModel().on({
        'beforeselect' : function(sm, node){
             return node.isLeaf();
        },
        'selectionchange' : function(sm, node){
            if(node){
                this.fireEvent('feedselect', node.attributes);
            }
            this.getTopToolbar().items.get('delete').setDisabled(!node);
        },
        scope:this
    });

    this.addEvents({feedselect:true});

    this.on('contextmenu', this.onContextMenu, this);
	
	this.hasfavorite = false;
};

Ext.extend(FeedPanel, Ext.tree.TreePanel, {

    onContextMenu : function(node, e){
        if(!this.menu){ // create context menu on first right click
            this.menu = new Ext.menu.Menu({
                id:'feeds-ctx',
                items: [{
                    id:'load',
                    iconCls:'load-icon',
                    text:'Загрузить',
                    scope: this,
                    handler:function(){
                        this.ctxNode.select();
                    }
                },
				{
					id:'rename',
                    text:'Переименовать',
                    iconCls:'feed-icon',
                    scope: this,
                    handler: function() {
						this.showRenameWindow(this.ctxNode.attributes);
						
						}
                },
				{
					id:'delete',
                    text:'Удалить',
                    iconCls:'delete-icon',
                    scope: this,
                    handler:function(){
					 	Ext.MessageBox.buttonText.yes = "Да";
						Ext.MessageBox.buttonText.no = "Нет";
						Ext.Msg.show({
						   title:'Удаление источника',
						   msg: 'Вы дейстивательно хотите удалить источник?',
						   buttons: Ext.Msg.YESNO,
						   fn: function (btn) {
									if (btn=="yes") {
										this.lastSelNode.ui.removeClass('x-node-ctx');
										this.removeFeed(this.lastSelNode.attributes.url);
										this.lastSelNode = null;
									}
								},
						   animEl: 'elId',
						   scope : this,
						   icon: Ext.MessageBox.WARNING 
						}); 
                    }
                }
				,'-',{
                    iconCls:'add-feed',
                    text:'Добавить источник',
                    handler: this.showWindow,
                    scope: this
                },'-',{
                    iconCls:'add-feed',
                    text:'Добавить в "Мои источники"',
                    handler: function() {
						this.addFeed(this.ctxNode.attributes);
						},
                    scope: this
                }
				]
            });
            this.menu.on('hide', this.onContextHide, this);
        }
        if(this.ctxNode){
            this.ctxNode.ui.removeClass('x-node-ctx');
            this.ctxNode = null;
        }
        if(node.isLeaf()){
			this.lastSelNode = node;
            this.ctxNode = node;
            this.ctxNode.ui.addClass('x-node-ctx');
            this.menu.items.get('load').setDisabled(node.isSelected());
            this.menu.showAt(e.getXY());
        }
		if (node.parentNode.attributes.def==1) {
			this.menu.items.get('delete').setDisabled(true);
			this.menu.items.get('rename').setDisabled(true);
		}else{
			this.menu.items.get('delete').setDisabled(false);
			this.menu.items.get('rename').setDisabled(false);
		}
    },

    onContextHide : function(){
        if(this.ctxNode){
            this.ctxNode.ui.removeClass('x-node-ctx');
            this.ctxNode = null;
        }
    },

    showWindow : function(btn){
        if(!this.win){
            this.win = new FeedWindow();
            this.win.on('validfeed', this.addFeed, this);
        }
        this.win.show(btn);
    },
	showFeed : function(url){
         Ext.Ajax.request({
            url: 'feed-proxy.php',
            params: {feed: url},
            success: this.validateFeed,
            scope: this,
            feedUrl: url
        });
    },
	validateFeed : function(response, options){
        var dq = Ext.DomQuery;
        var url = options.feedUrl;
        try{
            var json = Ext.util.JSON.decode(response.responseText);
			if (typeof(json.rss.channel)!="undefined") {
				var text = json.rss.channel.title;
				var description = json.rss.channel.description;
				this.addFeed({url: url,text: text},false,true);
				
            }
        }catch(e){
        }
    },
	
	showRenameWindow : function(btn){
        if(!this.rwin){
            this.rwin = new FeedRenameWindow();
            this.rwin.on('renamefeed', this.renameFeed, this);
        }
		this.rwin.setValues(arguments[0]);
        this.rwin.show(btn);
    },

    selectFeed: function(url){
        this.getNodeById(url).select();
    },
	
	renameFeed: function(attr){
        this.getNodeById(attr.url).setText(attr.text);
		//alert("SET "+attr.url);
    },

    removeFeed: function(url){
        var node = this.getNodeById(url);
        if(node){
            node.unselect();
            Ext.fly(node.ui.elNode).ghost('l', {
                callback: node.remove, scope: node, duration: .4
            });
        }
		var cp = new Ext.state.CookieProvider();
		var items = Ext.util.JSON.decode(cp.get("feeditems","{}"));
		items[url]=undefined;
		cp.set("feeditems",Ext.util.JSON.encode(items));
    },
 
    addFeed : function(attrs, inactive, preventAnim){
        var exists = this.getNodeById(attrs.url);
		//attrs.text = Ext.util.Format.ellipsis(attrs.text,55);
        if(exists){
            if(!inactive){
                exists.select();
                exists.ui.highlight();
            }
            return;
        }
        Ext.apply(attrs, {
            iconCls: 'feed-icon',
            leaf:true,
            cls:'feed',
            id: attrs.url,
			ftext : attrs.text,
			text: Ext.util.Format.ellipsis(attrs.text,35)
			
        });
        var node = new Ext.tree.TreeNode(attrs);
        this.feeds.appendChild(node);
        if(!inactive){
            if(!preventAnim){
                Ext.fly(node.ui.elNode).slideIn('l', {
                    callback: node.select, scope: node, duration: .4
                });
            }else{
                node.select();
            }
        }
		var cp = new Ext.state.CookieProvider();
		var items = Ext.util.JSON.decode(cp.get("feeditems","{}"));
		items[attrs.url.toString()] = attrs.text;
		cp.set("feeditems",Ext.util.JSON.encode(items));
        return node;
    },
	
	addDefFeed : function(attrs, inactive, preventAnim,feed_id){
        var exists = this.getNodeById(attrs.url+"_cat_"+feed_id)
		//attrs.text = Ext.util.Format.ellipsis(attrs.text,55);;
        if(exists){
            if(!inactive){
                exists.select();
                exists.ui.highlight();
            }
            return;
        }
        Ext.apply(attrs, {
            iconCls: 'feed-icon',
            leaf:true,
            cls:'feed',
            id: attrs.url+"_cat_"+feed_id
        });
        var node = new Ext.tree.TreeNode(attrs);
        dfeeds[feed_id].appendChild(node);
        if(!inactive){
            if(!preventAnim){
                Ext.fly(node.ui.elNode).slideIn('l', {
                    callback: node.select, scope: node, duration: .4
                });
            }else{
				node.select();
            }
			//dfeeds[feed_id].expand();
        }
        return node;
    },

    // prevent the default context menu when you miss the node
    afterRender : function(){
        FeedPanel.superclass.afterRender.call(this);
        this.el.on('contextmenu', function(e){
            e.preventDefault();
        });
    },
	loadFeeds: function () {
		if (feedsxml) {
			var jsonobj = feedsxml;
			var selFeed;
			var our_sub;
			for (var icat=0; icat<jsonobj.feeds.category.length; icat++) {
				if (icat==0) {
					our_sub=new Ext.tree.TreeNode({
								text:'Новости и Блоги',
								cls:'feeds-node',
								id: 'ourfeedstree',
								expanded:true
							});
					
						this.root.appendChild(our_sub);
				}
				 	dfeeds[jsonobj.feeds.category[icat].id] = our_sub.appendChild(
						new Ext.tree.TreeNode({
							text:jsonobj.feeds.category[icat].name,
							expanded:false,
							useArrows: true
						})
					);
					dfeeds[jsonobj.feeds.category[icat].id].attributes.def=1;
					var has_act=false;
					for (var ifeed=0; ifeed<jsonobj.feeds.category[icat].items.item.length; ifeed++) {
						var furl = jsonobj.feeds.category[icat].items.item[ifeed].url;
							furl = furl.replace(/\&amp;/g,"&");
							var items = Ext.util.JSON.decode(cp.get("feeditems","{}"));
							
						 if (!this.ctxNode && jsonobj.feeds.category[icat].items.item[ifeed].setdefault==1 && !this.hasfavorite) {
							dfeeds[jsonobj.feeds.category[icat].id].expand();
								this.addDefFeed({
								url:furl,
								text: jsonobj.feeds.category[icat].items.item[ifeed].text
								}, false, true,jsonobj.feeds.category[icat].id);
								
						}else{
							this.addDefFeed({
								url:furl,
								text: jsonobj.feeds.category[icat].items.item[ifeed].text
								}, true, true,jsonobj.feeds.category[icat].id);
						} 	
					} 
				}
		}
	}
});


